package com.example.demo.config;

import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author: 聂吉泽
 * @Description:
 * @Date: create in 2021/11/9 16:33
 */
@RestControllerAdvice(basePackages = "com.example.demo.web")
public class ResponseWrapperAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //处理返回值是String的情况
        if (o instanceof String) {
            return JSON.toJSONString(o);
        }
        return ResponseWrapper.ok(o);
    }
}
